#region Copyright & License
//
// Copyright 2010 sd&c Hofmann 
// 
// mailto:info@sdch.de
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.UserCode;
using Microsoft.Office.Server.Diagnostics;
using SDCH.SharePoint.Log4Sandbox.UserCode;
using System.Collections.Generic;

namespace SDCH.SharePoint.Log4Sandbox.Features
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("f272d5d6-a63a-4b3c-8d55-0425851eb124")]
    public class SDCHSharePointLog4SandboxProxyEventReceiver : SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                PortalLog.LogString("{0} Feature Activated class: {1}", "Enter", this.GetType().Name);

                RegisterProxyOperations();

                PortalLog.LogString("{0} Feature Activated class: {1}", "Leave", this.GetType().Name);

            }
            catch (Exception X)
            {
                PortalLog.LogString("{0} Feature Activated class: {1}", X.Message, this.GetType().Name);
            }

        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {

                PortalLog.LogString("{0} Feature Deactivating class: {1}", "Enter", this.GetType().Name);

                RemoveProxyOperations();

                PortalLog.LogString("{0} Feature Deactivating class: {1}", "Leave", this.GetType().Name);

            }
            catch (Exception X)
            {
                PortalLog.LogString("{0} Feature Deactivating class: {1}", X.Message, this.GetType().Name);

            }
        }

        private static void RegisterProxyOperations()
        {
            SPUserCodeService userCodeService = SPUserCodeService.Local;

            if (userCodeService != null)
            {
                foreach (SPProxyOperationType curOperationType in GetProxyOperationTypes())
                {
                    userCodeService.ProxyOperationTypes.Add(curOperationType);
                    userCodeService.Update();

                    PortalLog.LogString("Successfully registered proxy operation {0}", curOperationType.TypeName );
                }
            }
            else
            {
                PortalLog.LogString("UserCode Service not available. Could not activate proxy operation assembly {0}", LogContextManager.Log4SandboxAssemblyName);
            }
        }

        private static IEnumerable<SPProxyOperationType> GetProxyOperationTypes()
        {
            List<SPProxyOperationType> enOperationTypes = new List<SPProxyOperationType>();

            enOperationTypes.Add(new SPProxyOperationType(LogContextManager.Log4SandboxAssemblyName, LogContextManager.Log4SandboxGetLoggerOperationTypeName));
            enOperationTypes.Add(new SPProxyOperationType(LogContextManager.Log4SandboxAssemblyName, LogContextManager.Log4SandboxLogOperationTypeName));

            return enOperationTypes;
        }


        private static void RemoveProxyOperations()
        {
            SPUserCodeService userCodeService = SPUserCodeService.Local;

            if (userCodeService != null)
            {

                List<SPProxyOperationType> lLog4SandboxOperation = new List<SPProxyOperationType>();


                foreach (SPProxyOperationType curOperationType in userCodeService.ProxyOperationTypes)
                {
                    if (curOperationType.AssemblyName.Equals(LogContextManager.Log4SandboxAssemblyName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        lLog4SandboxOperation.Add(curOperationType);
                    }
                }

                foreach (SPProxyOperationType curOperationType in lLog4SandboxOperation)
                {
                    userCodeService.ProxyOperationTypes.Remove(curOperationType);
                    userCodeService.Update();
                    PortalLog.LogString("Successfully removed proxy operation {0}", curOperationType.TypeName);

                }
            }
            else
            {
                PortalLog.LogString("UserCode Service not available. Could not deactivate proxy operation of assembly {0}", LogContextManager.Log4SandboxAssemblyName);
            }
        }
    }
}
